﻿package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.badibadi.infos.ImageAttribute;
import com.badibadi.infos.MyFriendsModel;
import com.badibadi.infos.Record_array;
import com.badibadi.infos.Results;
import com.badibadi.infos.TempIMGAddressModel;
import com.badibadi.logic.ImgFileListActivity;
import com.badibadi.mytools.BitmapHelp;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Convert;
import com.badibadi.mytools.FriendsTool;
import com.badibadi.mytools.ImageLoader;
import com.badibadi.mytools.ImageTools;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.WidgetUtils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
//import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.MyGridView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CalendarContract.Attendees;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
//请将信息填写完整 Adapter
//第一记 sinaweibo 上传信息为空 up_img_item_addfriends_list StartTime zhan_name button_address Service_img_address Service_img_address OnActivity  addressModels_main
//record_first_new_add_record create_record

public class AddingRecordFirstActivity extends BaseActivity implements
		OnClickListener {

	private static final String TAG = "AddingRecordFirstActivity";
	private ImageView[] iv;
	private Bitmap[] bmp;
	private TextView startTime, endTime;
	public Item_Adapter adapter;// 这是个图片的adapter
	private MyGridView up_img_item_image;
	private ImageView up_img_item_addfriends;
	public List<TempIMGAddressModel> addressModels, addressModels_main;
	public ImageAttribute imageAttribute;
	public List<ImageAttribute> attributes;
	private LinearLayout button_address;
	private Results results, results2;
	private String temp_edit;
	private EditText image_description;

	private Friend_Item_Adapter friend_Item_Adapter;
	private Gallery up_img_item_addfriends_list;
	private List<MyFriendsModel> listObj_main;// @的好友的列表
	private Context context;
	protected boolean is_new_add;
	protected int rid_main, zhan_numm = 0;
	public DeletePicture deletePictrue;// 删除图片的接口
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// case 3000:
			// // if (!list.isEmpty()) {
			// // list.clear();
			// // }
			//
			// try {
			// imageAttribute = (ImageAttribute) msg.getData()
			// .getSerializable("img_info");
			// ++zhan_numm;
			// imageAttribute.setZhan_num(zhan_numm + "");
			// attributes.add(imageAttribute);
			// addressModels = new ArrayList<TempIMGAddressModel>();
			// if (imageAttribute.getArrayList() != null
			// && !imageAttribute.getArrayList().isEmpty()) {
			// for (int i = 0; i < imageAttribute.getArrayList()
			// .size(); i++) {
			// TempIMGAddressModel model = new TempIMGAddressModel();
			// model.setImg_address(imageAttribute.getArrayList()
			// .get(i));
			// addressModels.add(model);
			// }
			// }
			// addressModels_main.addAll(addressModels);
			// adapter.notifyDataSetChanged();
			// Utils.AddCity(AddingRecordFirstActivity.this,
			// imageAttribute.getCity_name(), button_address);
			// } catch (Exception e) {
			// // TODO: handle exception
			// }
			//
			// // AddCity(imageAttribute.getCity_name(), button_address);
			// break;
			case 1:
				Utils.ExitPrgress(AddingRecordFirstActivity.this);
				try {
					Utils.showMessage(AddingRecordFirstActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				Utils.ExitPrgress(AddingRecordFirstActivity.this);
				try {
					if (results.isRet()) {
						Utils.showMessage(AddingRecordFirstActivity.this,
								getResources().getString(R.string.l_xb23));
						if (is_new_add) {
							start_myself(context, ++TheCurrentIsWhich,
									Integer.valueOf(results.getRetmsg()));
						}
						Constants.is_shuaxin = true;
						finish();

					}
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(AddingRecordFirstActivity.this);
				try {
					Utils.showMessage(AddingRecordFirstActivity.this,
							getResources().getString(R.string.l_xb24));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:
				Utils.ExitPrgress(AddingRecordFirstActivity.this);
				try {
					Utils.showMessage(AddingRecordFirstActivity.this,
							getResources().getString(R.string.l_xb25));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 5:
				try {
					Utils.ExitPrgress(AddingRecordFirstActivity.this);
					TheCurrentIsWhich = Integer.valueOf(results2.getRetmsg());
					++TheCurrentIsWhich;
					init();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	// private LinearLayout StartTime,EndTime;
	/**
	 * 当前是第几记
	 */
	private int TheCurrentIsWhich;
	/** 第一记名称 */
	private EditText record_name;
	private String is_newcreate = null;
	private String record_id = null;
	public String cid = null;

	DisplayImageOptions options;
	Record_array array;

	/**
	 * AddingRecordFirstActivity(第一记和新增一记界面) 新增一记传入参数: startTime
	 * record_first_uppic_settings
	 * 
	 * is_newcreate:判断新增一记还是新增第一记("yes":新增第一记,"no":新增一记)
	 * 
	 * rid_main:记录id(is_newcreate="no"才传) startTime
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.record_first);

		array = (Record_array) getIntent().getSerializableExtra("array");
		//    
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		try {
			is_newcreate = getIntent().getStringExtra("is_newcreate");
			// record_id = getIntent().getStringExtra("record_id");
			rid_main = getIntent().getIntExtra("rid_main", 0);
			cid = getIntent().getStringExtra("cid");
			TheCurrentIsWhich = getIntent().getIntExtra("ji_num", 1);
		} catch (Exception e) {
			   
		}
//		   
		// rid_main = 82;
		// is_newcreate = "no";
		try {
			if (is_newcreate.equals("no")) {
				recordHeadJiNum(rid_main);
//				   
			} else if (is_newcreate.equals("yes")) {
//				   
				// TheCurrentIsWhich = 1;
				init();
			}
		} catch (Exception e) {
			   
		}

	}

	// private void AddCity(String name, LinearLayout v) {
	// Button button = new Button(AddingRecordFirstActivity.this);
	// button.setText(name);
	// button.setBackgroundResource(R.drawable.shape_blue_circular_bead_100);
	// button.setFocusable(false);
	// button.setFocusableInTouchMode(false);
	// button.setTextColor(getResources().getColor(R.color.white));
	// v.addView(button);
	// }

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		context = this;
		Constants.num_up_img_handler = handler;
	}

	private void start_myself(Context context, int s, int rid) {
		Intent intent = new Intent(context, AddingRecordFirstActivity.class);
		intent.putExtra("ji_num", s);
		intent.putExtra("rid_main", rid);
		intent.putExtra("is_newcreate", "yes");
		if (array != null) {
			intent.putExtra("array", array);
		}
		if (cid != null) {
			intent.putExtra("cid", cid);
		}
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	public void recordHeadJiNum(final int recordId) {
		Utils.showPrgress(AddingRecordFirstActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("recordId", recordId);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "record/recordHeadJiNum");
//				   
				if (content != null) {
					results2 = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   
//					
					if (results2 != null
							&& !results2.getRetmsg().equals("null")
							&& results2.isRet()) {
						handler.sendEmptyMessage(5);
					} else {
						handler.sendEmptyMessage(4);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	protected void init() {
		// TODO Auto-generated method stub
//		   
		Constants.START_TIME = null;
		Constants.END_TIME = null;
		is_new_add = false;
		addressModels_main = new ArrayList<TempIMGAddressModel>();
		listObj_main = new ArrayList<MyFriendsModel>();
		attributes = new ArrayList<ImageAttribute>();
		button_address = (LinearLayout) findViewById(R.id.button_address);
		up_img_item_image = (MyGridView) findViewById(R.id.up_img_item_image);
		image_description = (EditText) findViewById(R.id.image_description);
		up_img_item_addfriends_list = (Gallery) findViewById(R.id.up_img_item_addfriends_list);
		friend_Item_Adapter = new Friend_Item_Adapter(
				AddingRecordFirstActivity.this);
		up_img_item_addfriends_list.setAdapter(friend_Item_Adapter);
		up_img_item_addfriends = (ImageView) findViewById(R.id.up_img_item_addfriends);
		up_img_item_addfriends.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(AddingRecordFirstActivity.this,
						MyFriendsResultActivity.class);
				startActivityForResult(intent, 3);
			}
		});
		this.findViewById(R.id.record_first_uppic_settings).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						String tit = null, pers = null, con = null;
						is_new_add = false;
						tit = record_name.getText().toString().trim();
						con = image_description.getText().toString().trim();
						pers = FriendsTool.BackAllResult("sdf", listObj_main);

						if (Utils.Judge_Time(Constants.START_TIME,
								Constants.END_TIME)) {
							// Toast.makeText(getApplicationContext(), "新增一记",
							// 0).show();
							if (!StringUtil.isNullOrEmpty(tit)
									&& !StringUtil.isNullOrEmpty(con)) {
								if (rid_main != 0) {
									try {
										add_article(
												fengzhuang_article(
														Constants.START_TIME,
														Constants.END_TIME,
														tit, pers, con),
												fengzhuang_img_infos(),
												rid_main);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										   
									}
								} else {
									try {
										create_record(
												fengzhuang_article(
														Constants.START_TIME,
														Constants.END_TIME,
														tit, pers, con),
												fengzhuang_img_infos());
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										   
									}
								}
							} else {
								Toast.makeText(
										getApplicationContext(),
										getResources().getString(
												R.string.l_xb26), 0).show();
							}
						} else {
							Toast.makeText(getApplicationContext(),
									getResources().getString(R.string.l_xb27),
									0).show();
						}
					}
				});
		// up_img_item_addfriends.addTextChangedListener(new TextWatcher() {
		//
		// @Override
		// public void onTextChanged(CharSequence arg0, int arg1, int arg2,
		// int arg3) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void beforeTextChanged(CharSequence arg0, int arg1,
		// int arg2, int arg3) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void afterTextChanged(Editable arg0) {
		// temp_edit = arg0.toString();
		// //    (d);
		// if (temp_edit.length() > 0) {
		// Start_Other_Activity(temp_edit);// 只要文本框里改变，就将文本框内容传入方法内监听最后一个字符是否是@
		// }
		// }
		// });
		// mainList = new ArrayList<ArrayList<String>>();
		// list = new ArrayList<String>();
		adapter = new Item_Adapter(AddingRecordFirstActivity.this);
		up_img_item_image.setAdapter(adapter);

		iv = new ImageView[] { (ImageView) this.findViewById(R.id.sinaweibo),
				(ImageView) this.findViewById(R.id.wechat),
				(ImageView) this.findViewById(R.id.qq),
				(ImageView) this.findViewById(R.id.twitter),
				(ImageView) this.findViewById(R.id.facebook) };// toGrayscale
		bmp = new Bitmap[iv.length];
		for (int i = 0; i < iv.length; i++) {
			bmp[i] = ImageTools.loadBitmapFromView(this, iv[i]);
			iv[i].setImageBitmap(ImageTools.getGrayBitmap(bmp[i]));
		}

		this.findViewById(R.id.return_btn).setOnClickListener(this);
		startTime = (TextView) this.findViewById(R.id.startTime);
		startTime.setOnClickListener(this);
		endTime = (TextView) this.findViewById(R.id.endTime);
		endTime.setOnClickListener(this);
		this.findViewById(R.id.StartTime).setOnClickListener(this);
		this.findViewById(R.id.EndTime).setOnClickListener(this);
		this.findViewById(R.id.record_first_new_add_record).setOnClickListener(
				this);
		// 设置这是第几记
		TextView title = (TextView) this.findViewById(R.id.title);
		String xx = "" + TheCurrentIsWhich;// Convert.convert();
		WidgetUtils.setMyText(title,
				getResources().getString(R.string.TheXXRecorded), xx);
		// 设置这是第几记名称
		record_name = (EditText) this.findViewById(R.id.record_name);
		String XX = "" + TheCurrentIsWhich;// Convert.convert();
		WidgetUtils.setMyHintEditText(record_name,
				getResources().getString(R.string.TheXXName), XX);
		this.findViewById(R.id.cha).setOnClickListener(this);
		// Bitmap bmp=BitmapFactory.decodeResource(getResources(),
		// R.drawable.ic_launcher);
		// iv[0].setImageBitmap(ImageTools.getGrayBitmap(bmp));
	}

	// private void Start_Other_Activity(String content) {
	// if (content.substring(content.length() - 1, content.length()).equals(
	// "@")) {
	// Intent intent = new Intent(AddingRecordFirstActivity.this,
	// MyFriendsResultActivity.class);
	// startActivityForResult(intent, 3);
	// }
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/**
		 * at好友
		 */
		if (requestCode == 3 && resultCode == 3) {
//			   ("进入");
			// et_sendDynamic.setText(et_sendDynamic.getText().toString()+data.getStringExtra("result"));
			List<MyFriendsModel> listObj = (ArrayList<MyFriendsModel>) data
					.getSerializableExtra("result");
			for (int i = 0; i < listObj.size(); i++) {
				if (listObj.get(i).isJudge()) {
					listObj_main.add(listObj.get(i));
				}
			}
			if (listObj_main.size() > 0 && listObj_main.size() >= 3) {
				up_img_item_addfriends_list
						.setSelection(listObj_main.size() / 2 + 1);
			} else if (listObj_main.size() > 0 && listObj_main.size() == 2) {
				up_img_item_addfriends_list.setSelection(1);
			}
			friend_Item_Adapter.notifyDataSetChanged();

		}
		if (requestCode == 5 && resultCode == 5) {
			imageAttribute = (ImageAttribute) data
					.getSerializableExtra("img_info");
			++zhan_numm;
			imageAttribute.setZhan_num(zhan_numm + "");
			attributes.add(imageAttribute);
			addressModels = new ArrayList<TempIMGAddressModel>();
			// if (imageAttribute.getArrayList() != null
			// && !imageAttribute.getArrayList().isEmpty()) {
			// for (int i = 0; i < imageAttribute.getArrayList().size(); i++) {
			// TempIMGAddressModel model = new TempIMGAddressModel();
			// model.setImg_address(imageAttribute.getArrayList().get(i));
			// addressModels.add(model);
			// }
			// }
			// 这是为了将addressModels_main中保存的地址改成网络的，上面注释的是保存本地的
			if (imageAttribute.getService_img_address() != null
					&& !imageAttribute.getService_img_address().isEmpty()) {
				for (int i = 0; i < imageAttribute.getService_img_address()
						.size(); i++) {
					TempIMGAddressModel model = new TempIMGAddressModel();
//					LogUtils.d("imageAttribute.getService_img_address().get(i)="
//							+ imageAttribute.getService_img_address().get(i));
					String[] a = imageAttribute.getService_img_address().get(i)
							.split("/Public");
					for (int j = 0; j < a.length; j++) {
						TempIMGAddressModel tempIMGAddressModel = new TempIMGAddressModel();

						if (!a[j].equals("")) {
							String cc = "\\/Public" + a[j];
//							LogUtils.d("cc=" + cc);
							tempIMGAddressModel.setImg_address(cc);
							addressModels.add(tempIMGAddressModel);
						}

					}
				}
			}
			addressModels_main.addAll(addressModels);
			adapter.notifyDataSetChanged();
			Utils.AddCity(AddingRecordFirstActivity.this,
					imageAttribute.getCity_name(), button_address);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 返回记的内容
	 * 
	 * @return
	 * @throws JSONException
	 */
	private JSONObject fengzhuang_article(String stime, String etime,
			String title, String person, String content) throws JSONException {
		JSONObject object = new JSONObject();
		object.put("start_time", stime);
		object.put("end_time", etime);
		object.put("uid", Utils.getUid(AddingRecordFirstActivity.this));
		object.put("title", title);
		object.put("club_id", cid);
		object.put("participator", person);
		object.put("content", content);
		return object;
	}

	private JSONObject fengzhuang_img_infos() throws JSONException {
		// JSONArray array_main = new JSONArray();
		JSONObject object = new JSONObject();
		object.put("typeid", fengzhuang_typeid());
		object.put("attachment", fengzhuang_attachment());
		object.put("address", fengzhuang_address());
		object.put("info", fengzhuang_info());
		object.put("photo_id", fengzhuang_photo_id());
		object.put("map_x", fengzhuang_map_x());
		object.put("map_y", fengzhuang_map_y());
		object.put("zhan_num", fengzhuang_zhan_num());
		object.put("path", fengzhuang_path());
		object.put("is_show", fengzhuang_is_show());
		object.put("participator", fengzhuang_participator());
		// array_main.put(object);
		return object;
	}

	private JSONObject fengzhuang_path() throws JSONException {

		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			if (attributes.get(i).getService_img_address() != null
					&& !attributes.get(i).getService_img_address().isEmpty()) {
				String pa = "";
				for (int j = 0; j < attributes.get(i).getService_img_address()
						.size(); j++) {
					pa += attributes.get(i).getService_img_address().get(j);
				}
				object.put("" + i, pa);
			}
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_participator() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getCanyu_persons());
//			   
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_is_show() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getIs_displaydongtai());
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_photo_id() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getXiangceid());
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_zhan_num() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getZhan_num());
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_map_y() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getAddress_jingdu());
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_map_x() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getAddress_weidu());
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_info() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getInfo());
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_attachment() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getLaiyuan());
		}
//		   (object.toString());
		return object;

	}

	private JSONObject fengzhuang_address() throws JSONException {
		JSONObject object = null;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			object.put("" + i, attributes.get(i).getAbsolute_address());
		}
//		   (object.toString());
		return object;
	}

	private JSONObject fengzhuang_typeid() throws JSONException {
//		   ("开始");
		JSONObject object;
		object = new JSONObject();
		for (int i = 0; i < attributes.size(); i++) {
			String t = "";
//			   ("数" + i);
			//    ("数量是" + attributes.get(i).getBiaoqian_num());
			if (attributes.get(i).getBiaoqian_map() != null
					&& !attributes.get(i).getBiaoqian_map().isEmpty()) {
//				   ("数" + attributes.get(i).getBiaoqian_num());
				for (int j = 0; j < attributes.get(i).getBiaoqian_num(); j++) {
					if (attributes.get(i).getBiaoqian_map().get(j) != null) {
						t += attributes.get(i).getBiaoqian_map().get(j) + ",";
					}
				}
				if (!t.equals("")) {
					object.put(i + "", quchu_zuihou(t));
				}

			}
		}
//		   ("打印:" + object.toString());
		return object;
	}

	public String quchu_zuihou(String s) {
		return s.substring(0, s.length() - 1);
	}

	private void create_record(final JSONObject article, final JSONObject img) {
		Utils.showPrgress(AddingRecordFirstActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				if (array != null) {
					map.put("record", array.getArray_record());
				}
				map.put("article", article);
				map.put("img", img);
				//    ("提交上去的数据" + map.toString());
//				   
				String content = null;
				if (cid != null) {
					content = Utils.sendRequest(map, Constants.BadiUrl_1
							+ "record/clubAddRecord");
					//    ("record/clubAddRecord返回的结果是：" +
					// content);
//					   
				} else {
					content = Utils.sendRequest(map, Constants.BadiUrl
							+ "create_record");
//					   
					//    ("create_record返回的结果是：" + content);
				}
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						//    ("测试结果是:" + results.getRetmsg());
//						   
//								"2返回的结果是：" + content + "  "
//										+ results.getRetmsg());
						handler.sendEmptyMessage(2);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
//					   
//							"1返回的结果是：" + content + "  " + results.getRetmsg());
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void add_article(final JSONObject article, final JSONObject img,
			final int rid) {
		Utils.showPrgress(AddingRecordFirstActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("rid", rid);
				map.put("article", article);
				map.put("img", img);
				if (cid != null) {
					map.put("cid", cid);
				}
				//    ("新的一记提交上去的数据" + map.toString());
//				   
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "add_article");
//				   
				//    ("新的一记返回的结果是：" + content);

				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//    ("测试结果是:" + results.getRetmsg());
//						   
						handler.sendEmptyMessage(2);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	class Friend_Item_Adapter extends BaseAdapter {
		private Context context;

		public Friend_Item_Adapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listObj_main.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return listObj_main.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			LayoutInflater inflater = LayoutInflater.from(context);
			arg1 = inflater.inflate(R.layout.friends_gallery_item, null);
			if (!listObj_main.get(arg0).isJudge()) {
				arg1.setVisibility(View.GONE);
			} else {
				arg1.setVisibility(View.VISIBLE);
			}
			TextView gallery_item_text = (TextView) arg1
					.findViewById(R.id.gallery_item_text);
			ImageView gallery_item_cha = (ImageView) arg1
					.findViewById(R.id.gallery_item_cha);
			gallery_item_text.setText("@"
					+ listObj_main.get(arg0).getNickName());
			gallery_item_cha.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg10) {
					listObj_main.remove(arg0);
					Friend_Item_Adapter.this.notifyDataSetChanged();
				}
			});
			return arg1;
		}

	}

	public class Item_Adapter extends BaseAdapter {
		private Context context;

		public Item_Adapter(Context context) {
			this.context = context;

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return addressModels_main.size() + 1;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return addressModels_main.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View convertView, ViewGroup arg2) {
			if (arg0 < addressModels_main.size()) {
				// if (convertView == null) {
				// convertView = ViewHolder.buildView(context,
				// R.layout.sure_upimg_item_main, arg2);
				// }
				// ViewHolder viewHolder = (ViewHolder) convertView.getTag();
				LayoutInflater viewHolder = LayoutInflater.from(context);
				convertView = viewHolder.inflate(R.layout.sure_upimg_item_main,
						null);
				ImageView sure_upimg_item_img = (ImageView) convertView
						.findViewById(R.id.sure_upimg_item_img);
				if (addressModels_main.get(arg0).getImg_address()
						.startsWith("\\/Public")) {

					String bb = addressModels_main.get(arg0).getImg_address()
							.substring(1);
					// com.nostra13.universalimageloader.core.ImageLoader
					// .getInstance().displayImage(
					// Constants.BadiDownImgUrl + "/" + bb,
					// sure_upimg_item_img, options);
					new BitmapHelp().displayImage(
							AddingRecordFirstActivity.this,
							sure_upimg_item_img, Constants.BadiDownImgUrl + "/"
									+ bb);
					//    
					// + addressModels_main.get(arg0).getImg_address());
				} else {
					pathtobitmap(addressModels_main.get(arg0).getImg_address(),
							sure_upimg_item_img);
				}

				sure_upimg_item_img
						.setOnLongClickListener(new OnLongClickListener() {
							@Override
							public boolean onLongClick(View arg10) {
								new AlertDialog.Builder(context)
										.setTitle(
												getResources().getString(
														R.string.l_xb28))
										.setIcon(R.drawable.icon)
										.setMessage(
												getResources().getString(
														R.string.l_xb29))
										.setPositiveButton(
												getResources().getString(
														R.string.Yes),
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg20,
															int arg1) {
														// addressModels_main.get(arg0).getImg_address();
														if (deletePictrue != null) {
															deletePictrue
																	.deletePictrue(
																			arg0,
																			addressModels_main,
																			attributes);
														} else {
															addressModels_main
																	.remove(arg0);
															Notific();
														}

													}
												})
										.setNegativeButton(
												getResources().getString(
														R.string.No),
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg0,
															int arg1) {

													}
												}).show();
								return false;
							}
						});
			}

			if (addressModels_main.isEmpty()
					|| arg0 >= addressModels_main.size()) {
				LayoutInflater viewHolder = LayoutInflater.from(context);
				convertView = viewHolder
						.inflate(R.layout.sure_upimg_main, null);
				ImageView sure_upimg_item_img_add = (ImageView) convertView
						.findViewById(R.id.sure_upimg_item_img_add);
				sure_upimg_item_img_add
						.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								Intent intent = new Intent(context,
										ImgFileListActivity.class);
								intent.putExtra("no_dou", "yes");
								intent.putExtra("panduan", "set");
								if (cid != null) {
									intent.putExtra("club", cid);
								}
								startActivityForResult(intent, 5);
							}
						});
			}
			return convertView;
		}

		private void pathtobitmap(String p, ImageView im) {
			im.setImageBitmap(ImageLoader
					.decodeSampledBitmapFromResource(p, 60));
		}

		public void Notific() {
			Item_Adapter.this.notifyDataSetChanged();
		}

	}

	/**
	 * 主要用于删除图片
	 * 
	 * @param dPicture
	 */
	public void setOnDeletePictrueClistener(DeletePicture dPicture) {
		deletePictrue = dPicture;
		// deletePictrue.deletePictrue(position, addressModels_main);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.return_btn:
			finish();
			break;
		case R.id.StartTime:
			CalendarTools.getInstance().createDateDialog_1(this, startTime,
					"start");
			break;
		case R.id.startTime:
			CalendarTools.getInstance().createDateDialog_1(this, startTime,
					"start");
			break;
		case R.id.EndTime:
			CalendarTools.getInstance()
					.createDateDialog_1(this, endTime, "end");
			break;
		case R.id.endTime:
			CalendarTools.getInstance()
					.createDateDialog_1(this, endTime, "end");
			break;
		case R.id.cha:
			record_name.setText("");
			break;
		case R.id.record_first_new_add_record:
			String tit = null,
			pers = null,
			con = null;
			tit = record_name.getText().toString().trim();
			is_new_add = true;
			con = image_description.getText().toString().trim();
			pers = FriendsTool.BackAllResult("sdf", listObj_main);
			if (Utils.Judge_Time(Constants.START_TIME, Constants.END_TIME)) {
				// Toast.makeText(getApplicationContext(), "新增一记", 0).show();
				if (!StringUtil.isNullOrEmpty(tit)
						&& !StringUtil.isNullOrEmpty(con)) {
					if (rid_main != 0) {
						try {
							add_article(
									fengzhuang_article(Constants.START_TIME,
											Constants.END_TIME, tit, pers, con),
									fengzhuang_img_infos(), rid_main);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						try {
							create_record(
									fengzhuang_article(Constants.START_TIME,
											Constants.END_TIME, tit, pers, con),
									fengzhuang_img_infos());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					}
				} else {
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.l_xb26), 0)
							.show();
				}
			} else {
				Toast.makeText(getApplicationContext(),
						getResources().getString(R.string.l_xb27), 0).show();
			}
			break;
		}
	}

	public Friend_Item_Adapter getFriend_Item_Adapter() {
		return friend_Item_Adapter;
	}

	public void setFriend_Item_Adapter(Friend_Item_Adapter friend_Item_Adapter) {
		this.friend_Item_Adapter = friend_Item_Adapter;
	}

	public List<MyFriendsModel> getListObj_main() {
		return listObj_main;
	}

	public void setListObj_main(List<MyFriendsModel> listObj_main) {
		this.listObj_main = listObj_main;
	}

	// 删除图片的接口
	public interface DeletePicture {

		void deletePictrue(int position,
				List<TempIMGAddressModel> addressModels_main,
				List<ImageAttribute> attributes);
	}

	public Item_Adapter getAdapter() {
		return adapter;
	}

	public void setAdapter(Item_Adapter adapter) {
		this.adapter = adapter;
	}

}
